import { _decorator, Component, Node, Vec3 } from 'cc';
import { PathMove } from './PathMove'; // 确保根据实际路径导入
import { PathEvent } from './PathEvent';

const { ccclass, property } = _decorator;

@ccclass('PathEvent_ISOLookNextPoint')
export class PathEvent_ISOLookNextPoint extends PathEvent {


    public override addEvent() {
        if (this.pathMove) {

            // 处理路径开始事件
            this.pathMove.onPathStart = (index , allPathPoints) => {
                this.flipIfNeeded(this.target.worldPosition, allPathPoints[0]);
            };

            // 添加路径点完成事件
            for (let i = 0; i < this.pathMove.getPathPoints().length; i++) {
                this.pathMove.addPointCompleteEvent(i, (index , allPathPoints) => {
                    if (index + 1 >= allPathPoints.length) return; // 如果没有下一个点，则不做处理

                    this.flipIfNeeded(allPathPoints[index], allPathPoints[index + 1]);
                });
            }
        }
    }

    /**
     * 根据下一个路径点的位置，判断是否需要翻转目标物体
     * @param currentPoint - 当前路径点
     * @param nextPoint - 下一个路径点
     */
    private flipIfNeeded(currentPoint: Vec3, nextPoint: Vec3) {
        const direction = nextPoint.x - currentPoint.x;

        if (direction < 0) {
            // 下一个点在当前点的左侧，翻转目标物体（例如：使得X轴缩放为负）
            this.target.scale = new Vec3(-Math.abs(this.target.scale.x), this.target.scale.y, this.target.scale.z);
        } else if (direction > 0) {
            // 下一个点在当前点的右侧，恢复目标物体的正常方向
            this.target.scale = new Vec3(Math.abs(this.target.scale.x), this.target.scale.y, this.target.scale.z);
        }
    }
}
